﻿using Microsoft.AspNetCore.Routing.Matching;
using System.Collections.Generic;

public class NetHandler_UploadPhoto: GameServerMessageHandler
{
    public const string Key = "UploadPhoto";

    public static NetHandler_UploadPhoto NewHandler()
    {
        return new NetHandler_UploadPhoto();
    }

    protected override ISerialize NewData() => new UploadPhotoRequestData();

    public override void _Execute(TCPClient client, ISerialize _data)
    {
        UploadPhotoRequestData requestData = _data as UploadPhotoRequestData;

        GameDebug.Log($"用户{client.userID} 上传基本信息:{requestData?.texId}");

        UserServer user = Game.instance.GetUser(client.userID);

        ImageUrlResponseData response = new ImageUrlResponseData();

        if (user == null)
        {
            GameDebug.LogError($"找不到用户：{client.userID}");
            response.code = ErrorCode.UserNotFound;
        }
        else
        {
            if (requestData != null)
            {
                int texId = requestData.texId;
                Tex texData = requestData.tex;

                int setTextRet = 0;
                if (!Tex.IsNull(texData))
                {
                    setTextRet = TextureSaver.SaveUserTexture(client.userID, texId, texData.texWidth, texData.texHeight, texData.tex);

                    response.url = TextureSaver.GetUserTextureUrl(client.userID, texId);
                    GameDebug.Log($" 更新texture结果：setTextRet:{setTextRet}");
                }
                else
                {
                    TextureSaver.DeleteUserTexture(client.userID, texId);
                }
                user.data.UpdatePhotoInfo(texId, response.url);

                if (setTextRet >= 0)
                    response.code = 0;
                else
                    response.code = -1;
            }
            else
            {
                GameDebug.LogError($"requestData == null _data:{_data != null} type:{_data.GetType()}");
                response.code = -1;
            }
        }

        byte[] data = response.Write();
        this.SendResponse(client, Key, this.m_MessageReceived.seq, data);
    }
}
